<template>
  <div class="df-page-list">
    <n-card
      v-if="props.pageOptions.searchForm || props.pageOptions.table"
      :bordered="false"
      class="pro-card"
    >
      <DFForm
        v-if="props.pageOptions.searchForm"
        is-search-form
        :get-label-form="getSearchLabelForm"
        :label-width="searchFormLabelWidth"
        :route-name="searchFormRouteName"
        @register="queryFormregister"
        @submit="reloadTableFn"
        @reset="resetFn"
      >
        <template v-for="(_, slot) in $slots" #[slot]="{ model }">
          <slot :name="slot" :model="model" />
        </template>
      </DFForm>
      <div class="flex df-page-list-table-view">
        <template v-if="beforeTableSlotName">
          <slot :name="beforeTableSlotName" />
        </template>

        <div
          v-if="props.pageOptions.table && !props.pageOptions.table.noTable"
          class="df-page-list-table"
        >
          <DFTable
            ref="dfTableRef"
            v-model:expanded-row-keys="tableExpandedKeysList"
            :has-index="tableHasIndex"
            :columns="tableColumns"
            :request="loadTableDataFn"
            :row-key="(row) => (tableRowKeyFn ? tableRowKeyFn(row) : row[tableRowKey])"
            :action-column="tableActionColumn"
            :opera-column="tableOperaColumn"
            :is-get-field-info="tableIsGetFieldInfo"
            :route-name="tableRouteName"
            :get-field-info-list="getFieldInfoList"
            :set-field-info-list="setFieldInfoList"
            :after-request="tableSetAfterRequestDataFn"
            :indent="tableIndent"
            :children-key="tableChildrenKey"
            @update-check="onCheckedRowFn"
          />
        </div>

        <template v-if="afterTableSlotName">
          <slot :name="afterTableSlotName" />
        </template>
      </div>
    </n-card>

    <DFModal
      v-if="props.pageOptions.modalFormDialog"
      ref="dfModalRef"
      :width="modalWidth"
      :confirm-btn-show="modalType !== 'check'"
      :dialog-type-title="modalTypeTitle"
      @register="modalRegister"
      @on-ok="okModalFn"
    >
      <template v-if="beforeModalFormSlotName">
        <slot :name="beforeModalFormSlotName" />
      </template>

      <DFForm
        v-if="modalType !== 'check'"
        :label-placement="modalLabelPlacement"
        :get-label-form="getModalLabelForm"
        :label-width="modalFormLabelWidth"
        :route-name="modalFormRouteName"
        @register="modalFormRegister"
      >
        <template v-for="(_, slot) in $slots" #[slot]="{ model }">
          <slot :name="slot" :model="model" />
        </template>
      </DFForm>

      <DFDescriptions
        v-else
        ref="dfDescriptionsRef"
        :get-label-form="getDescriptionsLabelForm"
        :column="descriptionsColumn"
        :route-name="descriptionsRouteName"
        :label-width="descriptionsLabelWidth"
        :descriptions-list="descriptionsSchemas"
      >
        <template v-for="(_, slot) in $slots" #[slot]="{ model }">
          <slot :name="slot" :model="model" />
        </template>
      </DFDescriptions>

      <template v-if="afterModalFormSlotName">
        <slot :name="afterModalFormSlotName" />
      </template>
    </DFModal>

    <DFUploadFile
      v-if="showDFUploadFile"
      ref="dfUploadFile"
      is-import-data
      :import-template-file-type="importTemplateFileType"
      :upload-url="importFileUrl"
      @get-attachment-list="getAttachmentList"
    />
  </div>
</template>

<script lang="ts" setup name="DFPageList">
  import { cloneDeep } from 'lodash';
  import type { FormItemRule } from 'naive-ui';
  import { DFTable, DFTableAction } from '@/components/DFTable';
  import { DFForm, useForm } from '@/components/DFForm/index';
  import { DFModal, useModal } from '@/components/DFModal';
  import { useMixins } from '@/hooks/useMixins';
  import { checkZhCodeFn } from '@/utils/formCheck';
  import { getFieldInfoList, setFieldInfoList } from '@/api/common/index';

  interface Props {
    pageOptions?: {
      searchForm?: {
        // form数据
        labelWidthZh?: number; // form中文label宽度
        labelWidthEn?: number; // form英文label宽度
        getLabelForm?: string; // form语言模块(table/form)
        routeName?: string; // form国际化路由name
        formSchemas?: any[]; // form列表
      };
      table?: {
        // table数据
        hasSelection?: boolean; // table是否有勾选列
        hasCreate?: boolean; // table是否有创建人、创建时间、修改人和修改时间
        rowKey?: string; // table唯一值
        routeName?: string; // form国际化路由name
        columns?: any[]; // table表头
        operaColumn?: any[]; // table操作按钮列表
        action?: Object; // table操作栏配置
        requestFn?: Function; // table请求方法
        exportRequestFn?: Function; // table导出方法
        delRequestFn?: Function; // table删除方法
        noTable?: Boolean;
      };
      modalFormDialog?: {
        labelWidthZh?: number; // dialog表单中文label宽度
        labelWidthEn?: number; // dialog表单英文label宽度
        cols?: number; // dialog表格一行几列
        dialogWidth?: number; // dialog宽度
        getDataRowKey?: string; // dialog获取当前详情入参key值
        routeName?: string; // dialog表单国际化路由name
        layout?: string; // dialog表单展示类型（横向/纵向）
        getLabelForm?: string; // dialog表单语言模块(table/form)
        getDataFnDataKey?: string; // dialog获取当前详情数据返回的key值
        formSchemas?: any[]; // dialog表单列表
        dialogSubmitOtherData?: Object; // dialog提交合并的其他数据
        getDataFn?: Function; // dialog获取当前详情方法
        handleEditDataFn?: Function; // dialog手动处理获取当前详情数据方法
        addDataFn?: Function; // dialog新增方法
        updateDataFn?: Function; // dialog更新方法
        setDialogDataFn?: Function; // 设置dialog数据方法
        beforeOpenDialogFn?: Function; // 打开dialog之前方法
        setDialogSubmitDataFn?: Function; // 设置dialog提交数据方法
        beforeDialogSubmitFn?: Function; // dialog提交之前方法
        afterDialogSubmitFn?: Function; // dialog提交之后方法
        handleDialogSubmitFn?: Function; // 手动处理dialog提交数据的方法
        handleDialogSubmitErrorFn?: Function; // 手动处理dialog提交数据报错的方法
      };
    };
  }

  const props = withDefaults(defineProps<Props>(), {
    pageOptions: () => ({}),
  });

  const {
    handleDeleteFn, // 公用删除方法
    handleExportFn, // 公用导出方法
    routerGoFn, // 公用路由跳转方法
    message, // 公用提示方法
    t, // 公用国际化方法
    routerPage, // 路由页面
    language, // 当前语言
  } = useMixins();

  const dfUploadFile: any = ref(null);

  const dfTableRef: any = ref(null); // table对象

  const queryFormSchemas = ref([]); // form配置列表

  const tableColumns = ref([]); // table配置列表

  const apiFn: any = ref(null); // table请求方法

  const setApiDataFn: any = ref(null); // 手动设置请求表格值的方法

  const tableRowKey = ref('id'); // table唯一值

  const tableSetAfterRequestDataFn = ref(null); // table唯一值

  let tableExpandedKeysList = []; // table展开数组

  let tableHasIndex = true; // table有序号

  let tableIsGetFieldInfo = false; // table自定义表格

  let tableIndent = 10; // table展开indent

  let tableChildrenKey = 'children';

  let tableRowKeyFn: any = null;

  let getSearchLabelForm = 'table'; // 语言模块

  let searchFormRouteName = routerPage; // form国际化模块（默认当前页面）

  let searchFormLabelWidthZh = '100'; // form中文label宽度

  let searchFormLabelWidthEn = '100'; // form英文label宽度

  let modalFormLabelWidthZh = '80'; // dialog表单中文label宽

  let modalFormLabelWidthEn = '80'; // dialog表单英文label宽

  let modalFormRouteName = routerPage; // table国际化模块（默认当前页面）

  let tableRouteName = routerPage; // table国际化模块（默认当前页面）

  let descriptionsRouteName = routerPage; // 查看列表国际化模块（默认当前页面）

  const showDFUploadFile = ref(false);

  let importTemplateFileType: any = null;

  let importFileUrl: any = null;

  let exportTableKeys = null;

  const [queryFormregister, { getFieldsValue, setFieldsValue: setQueryFormFieldsValueFn }] =
    useForm({
      gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
      schemas: queryFormSchemas,
    }); // form配置方法

  const searchFormLabelWidth = computed(() =>
    language.value === 'zh' ? searchFormLabelWidthZh : searchFormLabelWidthEn
  );

  async function loadTableDataFn(res) {
    if (apiFn.value) {
      const entity = getFieldsValue();

      for (const i in entity) {
        if (entity[i] === null) {
          entity[i] = '';
        }
      }

      let data = { entity, ...res };

      if (setApiDataFn.value) data = await setApiDataFn.value(data);

      return await apiFn.value(data);
    }

    return null;
  } // table请求方法

  const searchFormBeforeResetFn: any = ref(null);

  const searchFormAfterResetFn: any = ref(null);

  const searchFormRequestFn: any = ref(null);

  // const afterReladTableFn: any = ref(null);

  function reloadTableFn(isResetPage = true) {
    if (searchFormRequestFn.value) {
      const entity = getFieldsValue();

      for (const i in entity) {
        if (entity[i] === null) {
          entity[i] = '';
        }
      }

      searchFormRequestFn.value({ entity });

      return;
    }

    if (dfTableRef.value) {
      if (dfTableRef.value.pagination && isResetPage) dfTableRef.value.pagination.page = 1;

      dfTableRef.value.clearRowKeysFn();

      checkedRowKeyList.value = [];

      checkedRowList.value = [];
      checkedAllRowList.value = [];

      dfTableRef.value.reload();

      // if (afterReladTableFn.value) {
      //  afterReladTableFn.value();
      // }
    }
  } // table重置方法

  async function resetFn() {
    if (searchFormBeforeResetFn.value) await searchFormBeforeResetFn.value();

    await reloadTableFn();

    if (searchFormAfterResetFn.value) await searchFormAfterResetFn.value();
  }

  const tableActionColumn: any = ref(null); // table操作栏配置

  const tableOperaColumn: any = ref(null); // table操作按钮配置

  const checkedRowKeyList = ref<string[]>([]); // table选中列的唯一值list

  const checkedRowList = ref([]); // table选中列的整个对象

  const checkedAllRowList = ref<any[]>([]); // table选中所有页的列的整个对象

  const dfDescriptionsRef: any = ref(null); // 查看列表对象

  const descriptionsSchemas: any = ref([]); // 查看列表

  let descriptionsLabelWidthZh = 100; // 查看列表中文label宽度

  let descriptionsLabelWidthEn = 100; // 查看列表label宽度

  let getDescriptionsLabelForm = 'table'; // 查看列表语言模块

  let descriptionsColumn = 2; // 查看列表列数

  let beforeTableSlotName = null; // 插槽名称

  let afterTableSlotName = null; // 插槽名称

  const descriptionsLabelWidth = computed(() =>
    language.value === 'zh' ? descriptionsLabelWidthZh : descriptionsLabelWidthEn
  );

  async function onCheckedRowFn(rowKeys = []) {
    if (rowKeys && rowKeys.length) {
      const rowKeysList: any[] = toRaw(rowKeys);

      const tableData = dfTableRef.value.getDataSource(true) || [];

      if (tableData && tableData.length) {
        const list: any = [];

        for (const item of rowKeysList) {
          const obj = tableData.find((tItem) => tItem[tableRowKey.value] === item);
          if (obj) {
            list.push(toRaw(obj));
            // 所有页选中数据
            if (
              checkedAllRowList.value.findIndex((cItem) => cItem[tableRowKey.value] === item) === -1
            )
              checkedAllRowList.value.push(toRaw(obj));
          }
        }
        // 所有页选中数据
        checkedAllRowList.value = checkedAllRowList.value.filter((cItem) =>
          rowKeysList.includes(cItem[tableRowKey.value])
        );
        checkedRowList.value = list;
      }

      checkedRowKeyList.value = rowKeysList;
    } else {
      checkedRowKeyList.value = [];

      checkedRowList.value = [];
      checkedAllRowList.value = [];
    }
  } // table选中列方法

  function setActionsFn(actionColumns: any = [], row, delRequestFn: any = null) {
    const actions: any = [];

    if (actionColumns && actionColumns.length) {
      for (const item of actionColumns) {
        const {
          label = '',
          disabled = null,
          click = null,
          hump = false,
          rowKey = null,
          isArray = true,
          hidden = false,
          prop = null,
          auth = null,
          fn = null,
        } = item;

        if (label) {
          actions.push({
            label,
            auth,
            type: 'primary',
            text: true,
            prop: prop || label,
            hidden: typeof hidden === 'function' ? hidden(row) : hidden,
            disabled: disabled ? disabled(row) : false,
            onClick: () => {
              if (click) {
                // 执行传入click事件
                click(row);
              } else {
                if (
                  label === 'add' ||
                  label === 'edit' ||
                  label === 'check' ||
                  label === 'print' ||
                  label === 'copy'
                ) {
                  if (hump) {
                    // 跳转
                    routerGoFn(label, row[rowKey || tableRowKey.value]);
                  } else if (label === 'edit' && modalFormSchemas.value?.length) {
                    // 弹窗
                    handleEditFn(row);
                  } else if (label === 'check' && descriptionsSchemas.value?.length) {
                    handleEditFn(row, 'check');
                  } else if (label === 'add' && modalFormSchemas.value?.length) {
                    // 弹窗
                    handleEditFn(row, 'add');
                  } else if (label === 'copy' && modalFormSchemas.value?.length) {
                    // 弹窗
                    handleEditFn(row, 'copy');
                  }
                }

                if (label === 'delete' && delRequestFn) {
                  // 删除
                  handleDeleteFn(
                    isArray ? [row[rowKey || tableRowKey.value]] : row[rowKey || tableRowKey.value],
                    delRequestFn,
                    () => {
                      reloadTableFn();
                      fn && fn();
                    }
                  );
                }
              }
            },
            hump,
          });
        }
      }
    }

    return actions;
  } // 设置table操作栏方法

  const editModalDisabled = ref(false); // 编辑弹窗字段不可编辑

  function getCompoentPropsFn(item: any) {
    let data: any = {};

    if (item) {
      const {
        componentProps = null,
        component = null,
        editDialogDisabled = false,
        minlength = null,
        maxlength = null,
        type = null,
        options = null,
        disabled = null,
      } = item;

      switch (component) {
        case 'NRadioGroup':
          data = {
            options: [],
          };
          break;

        case 'NSelect':
          data = {
            filterable: true,
            options: [],
          };
          break;

        default:
          data = {
            maxlength: 250,
            clearable: true,
          };
          break;
      }

      if (disabled) data.disabled = disabled;

      if (editDialogDisabled) data.disabled = editModalDisabled;

      if (minlength) data.minlength = minlength;

      if (maxlength) data.maxlength = maxlength;

      if (type) data.type = type;

      if (options) data.options = options;

      if (componentProps) {
        data = {
          ...data,
          ...componentProps,
        };
      }
    }

    return data;
  } // 组装form方法

  function getRulesFn(item: any) {
    let list: any = [];

    if (item) {
      const {
        required = false,
        rules = [],
        component = null,
        checkZhCode = false,
        requiredRulesType = null,
      } = item;

      if (rules && rules.length) {
        list = rules;
      } else {
        if (checkZhCode) {
          // 不支持中文和空格
          list.push({
            required,
            validator(_rule: FormItemRule, value: string) {
              return checkZhCodeFn(value, true);
            },
            trigger: ['blur'],
          });
        } else {
          if (required) {
            const rulesData: any = {
              required: true,
              message: t('common.formTipMsg.input'),
              trigger: [
                `${
                  [
                    'NSelect',
                    'NRadioGroup',
                    'NTreeSelect',
                    'NRadioButtonGroup',
                    'NCheckbox',
                    'NCheckboxGroup',
                    'NDatePicker',
                    'NMonthPicker',
                    'NRangePicker',
                    'NWeekPicker',
                    'NTimePicker',
                  ].includes(component)
                    ? 'change'
                    : 'blur'
                }`,
              ],
            };

            if (requiredRulesType) rulesData.type = requiredRulesType;

            list.push(rulesData);
          }
        }
      }
    }

    return list;
  } // 组装form校验规则方法

  function setFormSchemasFn(formSchemas: any = []) {
    const list: any = [];

    if (formSchemas && formSchemas.length) {
      for (const item of formSchemas) {
        const {
          label = '',
          prop = '',
          field = '',
          defaultValue = null,
          component = null,
          editDialogHidden = false,
          hidden = null,
        } = item;

        if (label) {
          // console.log(hidden);
          list.push({
            ...item,
            component: component || 'NInput',
            field: field || prop || label,
            hidden: hidden !== null ? hidden : editDialogHidden ? editModalDisabled : false,
            defaultValue:
              defaultValue || ['', 0].includes(defaultValue)
                ? defaultValue
                : getDefaultValueFn(item),
            componentProps: getCompoentPropsFn(item),
            rules: getRulesFn(item),
          });
        }
      }
    }

    // console.log(list);

    return list;
  } // 组装设置form列表方法

  function getDefaultValueFn(item) {
    let value: any = '';

    if (item) {
      const { component = '', componentProps = {}, defaultValue = undefined } = item;

      const { multiple = false, defaultValue: cDefaultValue = undefined } = componentProps;

      if (component) {
        switch (component) {
          case 'NSelect':
            value = multiple ? [] : null;
            break;
          case 'NDatePicker':
          case 'NTimePicker':
            value = defaultValue || cDefaultValue;
            break;
          case 'NTreeSelect':
            value = null;
            break;
          case 'NInputNumber':
            value = defaultValue || cDefaultValue;
            break;
          default:
            break;
        }
      }
    }

    return value;
  } // 设置form默认值方法

  function setOperaColumnBtnDisabledFn(item) {
    return computed(() => {
      let disabled = false;

      if (item) {
        const { label = '', prop = '' } = item;

        switch (prop || label) {
          case 'delete':
          case 'print':
            disabled = !toRaw(checkedRowKeyList.value).length;

            break;

          default:
            break;
        }
      }

      return disabled;
    });
  } // 设置table操作按钮置灰方法

  function getOperaWidthFn(actionColumns = []) {
    let width = 120;

    let widthEn = 120;

    const btnNum = actionColumns ? actionColumns.length : 0;

    switch (btnNum) {
      case 1:
        width = 90;
        widthEn = 105;
        break;
      case 3:
        width = 150;
        widthEn = 180;
        break;
      case 4:
        width = 180;
        widthEn = 260;
        break;
      case 5:
        width = 210;
        widthEn = 290;
        break;
      case 6:
        width = 240;
        widthEn = 320;
        break;
      default:
        break;
    }

    return { width, widthEn };
  } // 设置table操作栏宽度方法

  let modalEditData = {}; // 编辑dialog对象

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({}); // dialog配置方法

  const modalFormSchemas: any = ref([]); // dialog表单配置列表

  const modalType = ref('add'); // dialog类型

  let isOpenModal = false; // 是否打开dialog

  const modalFormCols = ref(1); // dialog表格一行几列

  const modalFormLayout = ref('horizontal'); // dialog表单展示类型（横向/纵向）

  const [
    modalFormRegister,
    { validate, getFieldsValue: getModalFormValFn, setFieldsValue, clearValidate },
  ] = useForm({
    gridProps: { cols: modalFormCols as any },
    layout: modalFormLayout,
    showActionButtonGroup: false,
    schemas: modalFormSchemas,
  }); // dialog表单配置方法

  const modalFormLabelWidth = computed(() =>
    language.value === 'zh' ? modalFormLabelWidthZh : modalFormLabelWidthEn
  );

  async function okModalFn() {
    try {
      const isSubmit = await validate();

      if (!isSubmit) modalSubmitFn();
    } catch (e) {
      console.log(e);

      setSubLoading(false);
    }
  } // dialog保存方法

  const addFn: any = ref(null); // dialog新增方法

  const updateFn: any = ref(null); // dialog更新方法

  const submitFn: any = ref(null); // dialog提交方法

  const getDetailsFn: any = ref(null); // dialog获取当前详情方法

  const handleEditDetailsFn: any = ref(null); // dialog手动处理获取当前详情数据方法

  const setGetDetailsDataFn: any = ref(null); // 设置dialog获取当前详情入参方法

  const setModalDataFn: any = ref(null); // 设置dialog数据方法

  const beforeOpenModalFn: any = ref(null); // 打开dialog之前方法

  const setModalSubmitDataFn: any = ref(null); // 设置dialog提交数据方法

  const beforeModalSubmitFn: any = ref(null); // dialog提交之前方法

  const afterModalSubmitFn: any = ref(null); // dialog提交之后方法

  const handleModalSubmitFn: any = ref(null); // 手动处理dialog提交数据的方法

  const handleModalSubmitErrorFn: any = ref(null); // 手动处理dialog提交数据报错的方法

  let modalSubmitoOtherData = {}; // dialog提交合并的其他数据

  let getDetailsRowKey = 'id'; // dialog获取当前详情入参key值

  let getDetailsKey = 'id';

  let getDetailsFnDataKey = 'data'; // dialog获取当前详情数据返回的key值

  let getModalLabelForm = 'table'; // dialog表单语言模块

  let modalWidth = 600; // dialog宽度

  let modalTypeTitle = ''; // dialog类型标题

  let modalLabelPlacement = 'top'; // dialog表单语言模块

  let beforeModalFormSlotName = null; // 插槽名称

  let afterModalFormSlotName = null; // 插槽名称

  async function modalSubmitFn() {
    try {
      let isSubmit = true;

      let data: any = { ...cloneDeep(getModalFormValFn()), ...modalSubmitoOtherData };

      if (beforeModalSubmitFn.value) {
        // 提交之前方法
        isSubmit = await beforeModalSubmitFn.value(data);
      }

      if (isSubmit) {
        let res: any = null;

        if (setModalSubmitDataFn.value)
          data = await setModalSubmitDataFn.value(data, modalType.value);

        switch (modalType.value) {
          case 'add':
          case 'copy':
            // data['password'] = encrypt(data.password);

            res = await addFn.value(data);
            break;
          case 'edit':
            res = await updateFn.value({ ...modalEditData, ...data });
            break;

          default:
            res = await submitFn.value(data);
            break;
        }

        if (handleModalSubmitFn.value) {
          await handleModalSubmitFn.value(res);
        } else {
          if (res) {
            const { message: msg = '' } = res;

            closeModal();

            msg && message.success(msg);

            reloadTableFn();

            if (afterModalSubmitFn.value) await afterModalSubmitFn.value(res);
          } else {
            setSubLoading(false);
          }
        }
      } else {
        setSubLoading(false);
      }
    } catch (e) {
      setSubLoading(false);

      if (handleModalSubmitErrorFn.value) handleModalSubmitErrorFn.value(e);

      console.log(e);
    }
  } // dialog表单提交方法

  async function openModalFn(type = 'add', data: any = null, titleText = '') {
    modalEditData = {};

    let open = true;

    try {
      if (beforeOpenModalFn.value) {
        // 打开dialog之前方法
        open = await beforeOpenModalFn.value(data || {}, type);
      }

      if (open) {
        editModalDisabled.value = type === 'edit';

        modalType.value = type;

        // console.log(type);

        openModal(type, titleText);

        if (data) modalEditData = cloneDeep(data);

        // console.log(data);

        if (type === 'check') {
          for (const item of descriptionsSchemas.value) {
            const {
              label = null,
              prop = null,
              field = null,
              checkPropFn = null,
              checkProp = null,
            } = item;

            item.value = checkPropFn
              ? await checkPropFn(data)
              : data[checkProp || prop || field || label] === 0
              ? 0
              : data[checkProp || prop || field || label] || '';
          }
          isOpenModal = false;
        } else {
          nextTick(() => {
            data && setFieldsValue(data);

            isOpenModal = false;
          });
        }
      } else {
        isOpenModal = false;
      }
    } catch (e) {
      console.log(e);

      isOpenModal = false;
    }
  } // 打开dialog方法

  async function handleAddFn() {
    if (!isOpenModal) {
      isOpenModal = true;

      try {
        let data = {};

        if (setModalDataFn.value) {
          // 手动设置dialog数据
          data = await setModalDataFn.value(data, 'add');
        }

        openModalFn('add', data);
      } catch (e) {
        console.log(e);

        isOpenModal = false;
      }
    }
  } // 打开新增dialog方法

  async function handleEditFn(recordRow: Recordable, type = 'edit') {
    if (!isOpenModal) {
      isOpenModal = true;

      try {
        let rowData = cloneDeep({ ...recordRow });
        // console.log('getDetailsFn.value', getDetailsFn.valuegetDetailsFn.value);

        if (getDetailsFn.value) {
          // 获取dialog详情数据
          let getDetailsData = {};

          if (setGetDetailsDataFn.value) {
            // 需要配置请求参数
            getDetailsData = await setGetDetailsDataFn.value(rowData);
          }

          if (getDetailsRowKey) {
            // 默认配置id
            getDetailsData[getDetailsKey] = recordRow[getDetailsRowKey];
          }

          // console.log(111)

          const res = await getDetailsFn.value(getDetailsData);

          // console.log(res)

          if (handleEditDetailsFn.value) {
            // 手动处理编辑数据
            rowData = await handleEditDetailsFn.value(res);
          } else {
            rowData = res[getDetailsFnDataKey];
          }
        }

        if (rowData) {
          let data = cloneDeep({ ...rowData });

          if (setModalDataFn.value) {
            // 手动设置dialog数据
            data = await setModalDataFn.value(data, type);
          }

          openModalFn(type, data);
        }
      } catch (e) {
        console.log(e);

        isOpenModal = false;
      }
    }
  } // 打开编辑dialog方法

  function getAttachmentList() {
    dfUploadFile && dfUploadFile.value && dfUploadFile.value.closeModalFn();

    reloadTableFn();
  }

  function initFn(props) {
    if (props) {
      const { pageOptions = {} } = props;

      const { searchForm = null, table = null, modalFormDialog = null } = pageOptions;

      if (searchForm) {
        // form数据配置
        const {
          formSchemas = [],
          getLabelForm = null,
          routeName = null,
          labelWidthZh = null,
          labelWidthEn = null,
          beforeResetFn = null,
          afterResetFn = null,
          requestFn = null,
        } = searchForm;

        if (formSchemas && formSchemas.length)
          queryFormSchemas.value = setFormSchemasFn(formSchemas);

        if (getLabelForm) {
          // 语言模块
          getSearchLabelForm = getLabelForm;
        }

        if (routeName) {
          searchFormRouteName = routeName;
        }

        if (labelWidthZh) {
          searchFormLabelWidthZh = labelWidthZh;
        }

        if (labelWidthEn) {
          searchFormLabelWidthEn = labelWidthEn;
        }

        if (beforeResetFn) {
          searchFormBeforeResetFn.value = beforeResetFn;
        }

        if (afterResetFn) {
          searchFormAfterResetFn.value = afterResetFn;
        }

        if (requestFn) {
          searchFormRequestFn.value = requestFn;
        }
      }

      if (table) {
        // table数据配置
        const {
          columns = [],
          action = {},
          operaColumn = [],
          hasSelection = false,
          hasCreate = true,
          rowKey = '',
          requestFn = () => {},
          setRequestDataFn = null,
          exportRequestFn = null,
          delRequestFn = null,
          routeName = null,
          isGetFieldInfo = true,
          hasIndex = true,
          setAfterRequestDataFn = null,
          expandedKeysList = null,
          indent = null,
          childrenKey = null,
          rowKeyFn = null,
          sorter = true,
          beforeSlotName = null,
          afterSlotName = null,
          importUrl = null,
          importTemplateType = null,
          exportKeys = null,
        } = table;

        const { columns: actionColumns = [] } = action;

        if (rowKey) {
          // table列的唯一值
          tableRowKey.value = rowKey;
        }

        if (columns && columns.length) {
          const list: any = [];

          if (hasSelection) {
            // 多选
            list.push({
              width: 60,
              type: 'selection',
              key: 'selection',
              fixed: 'left',
            });
          }

          for (const item of columns) {
            const { label = '', key = '', prop = '', width = null } = item;

            if (label) {
              const obj = {
                sorter,
                ...item,
                key: key || prop || label,
              };

              if (!width) obj.width = 170;

              list.push(obj);
            }
          }

          if (hasCreate) {
            // 默认都有创建人、创建时间、修改人和修改时间
            list.push(
              {
                width: 160,
                label: 'createTime',
                common: true,
                key: 'createTime',
                sorter,
              },
              {
                width: 120,
                label: 'createByName',
                common: true,
                key: 'createName',
                sorter,
              },
              {
                width: 160,
                label: 'updateTime',
                common: true,
                key: 'updateTime',
                sorter,
              },
              {
                width: 120,
                label: 'updateByName',
                common: true,
                key: 'updateName',
                sorter,
              }
            );
          }

          // console.log(list);

          tableColumns.value = list;
        }

        if (actionColumns && actionColumns.length) {
          // table操作栏配置
          const newAction = cloneDeep(action);

          const { width, widthEn } = getOperaWidthFn(actionColumns);

          delete newAction.columns;

          tableActionColumn.value = {
            width,
            widthEn,
            label: 'operation',
            key: 'action',
            fixed: 'right',
            common: true,
            render(record) {
              const recordRow = toRaw(record);

              return h(DFTableAction as any, {
                style: 'button',
                actions: setActionsFn(actionColumns, recordRow, delRequestFn),
              });
            },
            ...newAction,
          };
        }

        if (operaColumn && operaColumn.length) {
          // table操作按钮配置
          const list: any = [];

          for (const item of operaColumn) {
            const {
              label = '',
              disabled = null,
              click = null,
              hump = false,
              prop = '',
              isArray = true,
            } = item;
            // console.log(item, 5555555);
            if (label) {
              list.push({
                ...item,
                label,
                prop: prop || label,
                hump,
                bind: {
                  disabled: disabled
                    ? // disabled(computed(() => toRaw(checkedRowKeyList.value)))
                      computed(() => disabled(toRaw(checkedRowKeyList.value)))
                    : setOperaColumnBtnDisabledFn(item), // 默认table操作按钮置灰方法
                  type: item.type || 'default',
                  'on-click': async () => {
                    if (click) {
                      // 手动传入点击方法
                      click(toRaw(checkedRowList.value), toRaw(checkedAllRowList.value));
                    } else {
                      if (label === 'add' || prop === 'add') {
                        // 新增
                        if (hump) {
                          // 路由跳转方法
                          routerGoFn();
                        } else if (modalFormSchemas.value.length) {
                          // 打开dialog方法
                          handleAddFn();
                        }
                      }

                      if (
                        label === 'delete' ||
                        prop === 'delete' ||
                        label === 'export' ||
                        prop === 'export'
                      ) {
                        const checkedRowKeyListValue = toRaw(checkedRowKeyList.value);
                        if (checkedRowKeyListValue && checkedRowKeyListValue.length) {
                          if (label === 'delete' || prop === 'delete') {
                            const rowKeyList = toRaw(checkedRowKeyList.value);
                            // 删除
                            handleDeleteFn(
                              isArray ? rowKeyList : rowKeyList.join(','),
                              delRequestFn,
                              reloadTableFn
                            );
                          }
                        }

                        if (
                          (label === 'export' || prop === 'export') &&
                          exportRequestFn &&
                          dfTableRef.value
                        ) {
                          // 导出

                          const { pageNum = 1, pageSize = 10 } =
                            dfTableRef?.value?.pagination || {};

                          let exportData = {
                            entity: {
                              ...getFieldsValue(),
                            },
                            pageSize,
                            pageNum,
                          };

                          for (const i in exportData.entity) {
                            if (exportData.entity[i] === null) {
                              exportData.entity[i] = '';
                            }
                          }

                          if (setApiDataFn.value) {
                            exportData = await setApiDataFn.value(exportData);
                          }

                          handleExportFn(
                            exportData,
                            checkedRowKeyList.value,
                            exportRequestFn,
                            exportTableKeys || 'ids'
                          );
                        }
                      }

                      if (
                        (label === 'import' || prop === 'import') &&
                        dfUploadFile.value &&
                        dfTableRef.value
                      )
                        dfUploadFile.value.openDialog();
                    }
                  },
                },
              });
              list.forEach((m, i) => {
                if (i === 0 && !m.bind.type) m.bind.type = 'primary';
                else if (i !== 0 && !m.bind.type) m.bind.type = 'default';
              });
            }

            if (label === 'import' || prop === 'import') showDFUploadFile.value = true;
          }

          tableOperaColumn.value = list;
        }

        if (requestFn) {
          // 请求方法配置
          apiFn.value = requestFn;
        }

        if (setRequestDataFn) setApiDataFn.value = setRequestDataFn;

        if (setAfterRequestDataFn) tableSetAfterRequestDataFn.value = setAfterRequestDataFn;

        if (routeName) tableRouteName = routeName;

        if (isGetFieldInfo) tableIsGetFieldInfo = isGetFieldInfo;

        if (expandedKeysList) tableExpandedKeysList = expandedKeysList;

        if (indent) tableIndent = indent;

        if (tableChildrenKey) tableChildrenKey = childrenKey;

        if (rowKeyFn) tableRowKeyFn = rowKeyFn;

        if (beforeSlotName) beforeTableSlotName = beforeSlotName;

        if (afterSlotName) afterTableSlotName = afterSlotName;

        if (importUrl) importFileUrl = importUrl;

        if (importTemplateType) importTemplateFileType = importTemplateType;

        if (exportKeys) exportTableKeys = exportKeys;

        tableHasIndex = hasIndex;
      }

      if (modalFormDialog) {
        // dialog配置
        const {
          formSchemas = [],
          getDataFnDataKey = null,
          getDataRowKey = null,
          getDataKey = null,
          getDataFn = null,
          setGetDataFn = null,
          handleEditDataFn = null,
          addDataFn = null,
          updateDataFn = null,
          submitDataFn = null,
          setDialogDataFn = null,
          beforeOpenDialogFn = null,
          getLabelForm = null,
          dialogSubmitOtherData = null,
          setDialogSubmitDataFn = null,
          beforeDialogSubmitFn = null,
          afterDialogSubmitFn = null,
          handleDialogSubmitFn = null,
          handleDialogSubmitErrorFn = null,
          routeName = null,
          labelWidthZh = null,
          labelWidthEn = null,
          layout = null,
          cols = null,
          dialogWidth = null,
          labelPlacement = null,
          typeTitle = null,
          descriptionsList = null,
          getDescriptionsListLabelForm = null,
          descriptionsListLabelWidthZh = null,
          descriptionsListLabelWidthEn = null,
          descriptionsListRouteName = null,
          descriptionsListColumn = null,
          beforeSlotName = null,
          afterSlotName = null,
        } = modalFormDialog;

        if (formSchemas && formSchemas.length) {
          // 配置dialog表单
          const list = setFormSchemasFn(formSchemas);

          // console.log(list);

          modalFormSchemas.value = list;

          if (!descriptionsSchemas.value || !descriptionsSchemas.value?.length)
            descriptionsSchemas.value = cloneDeep(list);

          // console.log(descriptionsSchemas.value);
        }

        if (addDataFn) {
          // 配置dialog新增方法
          addFn.value = addDataFn;
        }

        if (updateDataFn) {
          // 配置dialog更新方法
          updateFn.value = updateDataFn;
        }

        if (submitDataFn) {
          // 配置dialog更新方法
          submitFn.value = submitDataFn;
        }

        if (getDataFn) {
          // 配置获取dialog数据方法
          getDetailsFn.value = getDataFn;
        }

        if (setGetDataFn) {
          // 设置获取数据方法
          setGetDetailsDataFn.value = setGetDataFn;
        }

        if (handleEditDataFn) {
          // 配置处理获取dialog数据方法
          handleEditDetailsFn.value = handleEditDataFn;
        }

        if (getDataRowKey) {
          // 配置请求dialog数据key值
          getDetailsRowKey = getDataRowKey;
        }

        if (getDataKey) getDetailsKey = getDataKey;

        if (getDataFnDataKey) {
          // 配置请求dialog数据返回的key值
          getDetailsFnDataKey = getDataFnDataKey;
        }

        if (getLabelForm) {
          // 配置dialog语言模块
          getModalLabelForm = getLabelForm;
        }

        if (dialogSubmitOtherData) {
          // 配置dialog提交数据时需添加的其他数据
          modalSubmitoOtherData = dialogSubmitOtherData;
        }

        if (setDialogDataFn) {
          // 配置手动设置dialog提交的数据方法
          setModalDataFn.value = setDialogDataFn;
        }

        if (beforeOpenDialogFn) {
          // 配置打开dialog之前的方法
          beforeOpenModalFn.value = beforeOpenDialogFn;
        }

        if (setDialogSubmitDataFn) {
          // 配置设置dialog提交数据的方法
          setModalSubmitDataFn.value = setDialogSubmitDataFn;
        }

        if (beforeDialogSubmitFn) {
          // 配置设置dialog提交数据之前的方法
          beforeModalSubmitFn.value = beforeDialogSubmitFn;
        }

        if (afterDialogSubmitFn) {
          // 配置设置dialog提交数据成功之后的方法
          afterModalSubmitFn.value = afterDialogSubmitFn;
        }

        if (handleDialogSubmitFn) {
          // 配置手动处理dialog提交数据的方法
          handleModalSubmitFn.value = handleDialogSubmitFn;
        }

        if (handleDialogSubmitErrorFn) {
          // 配置手动处理dialog提交数据报错的方法
          handleModalSubmitErrorFn.value = handleDialogSubmitErrorFn;
        }

        if (routeName) {
          modalFormRouteName = routeName;

          descriptionsRouteName = routeName;
        }

        if (labelWidthZh) modalFormLabelWidthZh = labelWidthZh;

        if (labelWidthEn) modalFormLabelWidthEn = labelWidthEn;

        if (cols) modalFormCols.value = cols;

        if (layout) modalFormLayout.value = layout;

        if (labelPlacement) modalLabelPlacement = labelPlacement;

        if (typeTitle) modalTypeTitle = typeTitle;

        if (dialogWidth) modalWidth = dialogWidth;

        if (descriptionsList && descriptionsList.length)
          descriptionsSchemas.value = descriptionsList;

        if (getDescriptionsListLabelForm) getDescriptionsLabelForm = getDescriptionsListLabelForm;

        if (descriptionsListLabelWidthZh) descriptionsLabelWidthZh = descriptionsListLabelWidthZh;

        if (descriptionsListLabelWidthEn) descriptionsLabelWidthEn = descriptionsListLabelWidthEn;

        if (descriptionsListRouteName) descriptionsRouteName = descriptionsListRouteName;

        if (descriptionsListColumn) descriptionsColumn = descriptionsListColumn;

        if (beforeSlotName) beforeModalFormSlotName = beforeSlotName;

        if (afterSlotName) afterModalFormSlotName = afterSlotName;
      }
    }
  } // 数据初始化方法

  initFn(props); // 数据初始化

  defineExpose({
    getAttachmentList,
    checkedRowKeyList, // 表格勾选的数据的key的集合
    checkedRowList, // 表格勾选的数据集合
    checkedAllRowList, // 表格勾选的所有页的数据集合
    setQueryFormFieldsValueFn, // 设置查询表单的值
    openModalFn, // 打开弹窗
    reloadTableFn, // 重新加载表格(返回第一页,清除勾选状态和勾选数据,保留查询条件)
    setSubLoading, // 设置弹窗确认按钮loading状态
    closeModalFn: closeModal, // 关闭弹窗
    setFieldsValueFn: setFieldsValue, // 设置弹窗表单的值
    getFieldsValueFn: getFieldsValue, // 获取查询表单的值
    getModalFormValFn, // 获取弹窗表单的值
    clearValidate, // 清楚弹窗表单验证
    validate, // 弹窗表单验证
  }); // 暴露现有组件方法
</script>

<style lang="less" scoped>
  .df-page-list {
    .pro-card {
      border-radius: 4px;
      min-height: calc(100vh - 130px);
    }

    .df-page-list-table-view {
      width: 100%;
      // overflow: hidden;
      justify-content: space-between;

      .df-page-list-table {
        flex: 1;
        width: 100%;
      }
    }
  }
</style>
